package org.example.school.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.school.common.Context;
import org.example.school.common.Result;
import org.example.school.entity.*;
import org.example.school.model.dto.ExamScoreDTO;
import org.example.school.model.dto.TeacherProfileDTO;
import org.example.school.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class ExamInfo extends CommonInfo {

    @Autowired
    private IExamsService examsService;

    @Autowired
    private IScoresService scoresService;

    @Autowired
    private IClassesService classesService;

    @Autowired
    private ITeacherClassRelationsService teacherClassRelationsService;

    @Autowired
    private IStudentsService studentsService;

    @Autowired
    private ISubjectsService subjectsService;

    /**
     * 教师发布考试
     * @param exam 考试信息
     * @return 发布结果
     */
    public Result<String> publishExam(Exams exam) {
        try {
            // 获取当前教师信息
            Teachers teacher = this.getUserByTeacher().getData();
            if (teacher == null) {
                return Result.error("教师信息不存在");
            }

            // 检查教师是否有权限在该班级发布考试
            List<TeacherClassRelations> relations = teacherClassRelationsService.lambdaQuery()
                    .eq(TeacherClassRelations::getTeacherId, teacher.getId())
                    .list();

            List<Integer> classIds = relations.stream()
                    .map(TeacherClassRelations::getClassId)
                    .collect(Collectors.toList());

            if (!classIds.contains(exam.getClassId())) {
                return Result.error("无权限在该班级发布考试");
            }

            // 设置考试信息
            exam.setTeacherId(teacher.getId());
            boolean saved = examsService.save(exam);

            if (saved) {
                //批量生成考试成绩记录
                List<Students> studentsList = studentsService.lambdaQuery().eq(Students::getClassId, exam.getClassId()).list();
                List<Scores> scoresList = studentsList.stream().map(student -> {
                    Scores score = new Scores();
                    score.setExamId(exam.getId());
                    score.setStudentId(student.getId());
                    score.setRecordedByTeacherId(teacher.getId());
                    score.setSubjectId(exam.getSubjectId());
                    return score;
                }).collect(Collectors.toList());
                scoresService.saveBatch(scoresList);
                return Result.success("考试发布成功");
            } else {
                return Result.error("考试发布失败");
            }
        } catch (Exception e) {
            return Result.error("考试发布异常: " + e.getMessage());
        }
    }

    /**
     * 获取教师可以发布考试的班级列表
     * @return 班级列表
     */
    public Result<List<Classes>> getTeachingClasses() {
        try {
            // 获取当前教师信息
            Teachers teacher = this.getUserByTeacher().getData();
            if (teacher == null) {
                return Result.error("教师信息不存在");
            }

            // 获取教师任课关系
            List<TeacherClassRelations> relations = teacherClassRelationsService.lambdaQuery()
                    .eq(TeacherClassRelations::getTeacherId, teacher.getId())
                    .list();

            List<Integer> classIds = relations.stream()
                    .map(TeacherClassRelations::getClassId)
                    .collect(Collectors.toList());

            if (classIds.isEmpty()) {
                return Result.success(null);
            }

            // 查询班级信息
            List<Classes> classes = classesService.lambdaQuery()
                    .in(Classes::getId, classIds)
                    .list();

            return Result.success(classes);
        } catch (Exception e) {
            return Result.error("查询班级列表异常: " + e.getMessage());
        }
    }

    /**
     * 获取考试列表
     * @param classId 班级ID
     * @return 考试列表
     */
    public Result<List<Exams>> getExamList(Integer classId) {
        try {
            // 获取当前教师信息
            Teachers teacher = this.getUserByTeacher().getData();
            if (teacher == null) {
                return Result.error("教师信息不存在");
            }

            // 检查教师是否有权限查看该班级的考试
            List<TeacherClassRelations> relations = teacherClassRelationsService.lambdaQuery()
                    .eq(TeacherClassRelations::getTeacherId, teacher.getId())
                    .list();

            List<Integer> classIds = relations.stream()
                    .map(TeacherClassRelations::getClassId)
                    .collect(Collectors.toList());

            if (!classIds.contains(classId)) {
                return Result.error("无权限查看该班级考试");
            }

            // 查询考试列表
            List<Exams> exams = examsService.lambdaQuery()
                    .eq(Exams::getClassId, classId)
                    .eq(Exams::getTeacherId, teacher.getId())
                    .orderByDesc(Exams::getExamDate)
                    .list();

            return Result.success(exams);
        } catch (Exception e) {
            return Result.error("查询考试列表异常: " + e.getMessage());
        }
    }

    /**
     * 录入学生考试成绩
     * @param examId 考试ID
     * @param scores 成绩列表
     * @return 录入结果
     */
    public Result<String> recordScores(Long examId, List<Scores> scores) {
        try {
            // 检查考试是否存在
            Exams exam = examsService.getById(examId);
            if (exam == null) {
                return Result.error("考试不存在");
            }

            // 获取当前教师信息
            Teachers teacher = this.getUserByTeacher().getData();
            if (teacher == null) {
                return Result.error("教师信息不存在");
            }

            // 检查教师是否有权限录入该考试成绩
            if (!exam.getTeacherId().equals(String.valueOf(teacher.getId()))) {
                return Result.error("无权限录入该考试成绩");
            }

            // 检查该考试是否已经有成绩录入
            List<Scores> existingScores = scoresService.lambdaQuery()
                    .eq(Scores::getExamId, examId)
                    .list();

            if (!existingScores.isEmpty()) {
                return Result.error("该考试成绩已录入，如需修改请使用成绩修改功能");
            }

            // 设置成绩信息
            scores.forEach(score -> {
                score.setExamId(examId);
                score.setRecordedByTeacherId(teacher.getId());
                score.setRecordedAt(java.time.LocalDateTime.now());
            });

            // 批量保存成绩
            boolean saved = scoresService.saveBatch(scores);

            if (saved) {
                return Result.success("成绩录入成功");
            } else {
                return Result.error("成绩录入失败");
            }
        } catch (Exception e) {
            return Result.error("成绩录入异常: " + e.getMessage());
        }
    }

    /**
     * 获取考试成绩列表
     * @param examId 考试ID
     * @return 成绩列表
     */
    public Result<List<ExamScoreDTO>> getScoresByExamId(Long examId) {
        try {
            // 检查考试是否存在
            Exams exam = examsService.getById(examId);
            if (exam == null) {
                return Result.error("考试不存在");
            }

            // 获取当前教师信息
            Teachers teacher = this.getUserByTeacher().getData();
            if (teacher == null) {
                return Result.error("教师信息不存在");
            }

            // 检查教师是否有权限查看该考试成绩
            boolean equals = teacher.getId().equals(exam.getTeacherId());
            if (!equals) {
                return Result.error("无权限查看该考试成绩");
            }

            // 查询成绩列表
            List<Scores> scores = scoresService.lambdaQuery()
                    .eq(Scores::getExamId, examId)
                    .list();
            
            // 转换为ExamScoreDTO
            List<ExamScoreDTO> examScores = scores.stream().map(score -> {
                ExamScoreDTO examScoreDTO = new ExamScoreDTO();
                examScoreDTO.setId(score.getId());
                examScoreDTO.setExamId(score.getExamId());
                examScoreDTO.setStudentId(score.getStudentId());
                examScoreDTO.setSubjectId(score.getSubjectId());
                examScoreDTO.setScore(score.getScore());
                examScoreDTO.setRecordedByTeacherId(score.getRecordedByTeacherId());
                examScoreDTO.setRecordedAt(score.getRecordedAt());
                
                // 获取学生信息
                Students student = studentsService.getById(score.getStudentId());
                if (student != null) {
                    examScoreDTO.setStudentNumber(student.getStudentNumber());
                    examScoreDTO.setStudentName(student.getFullName());
                }
                
                return examScoreDTO;
            }).collect(Collectors.toList());

            return Result.success(examScores);
        } catch (Exception e) {
            return Result.error("查询成绩列表异常: " + e.getMessage());
        }
    }

    /**
     * 更新学生成绩
     * @param scoreId 成绩ID
     * @param newScore 新分数
     * @return 更新结果
     */
    public Result<String> updateScore(Long scoreId, String newScore) {
        try {
            // 检查成绩记录是否存在
            Scores score = scoresService.getById(scoreId);
            if (score == null) {
                return Result.error("成绩记录不存在");
            }

            // 获取当前教师信息
            Teachers teacher = this.getUserByTeacher().getData();
            if (teacher == null) {
                return Result.error("教师信息不存在");
            }

            // 检查教师是否有权限修改该成绩
            Exams exam = examsService.getById(score.getExamId());
            boolean equals = teacher.getId().equals(exam.getTeacherId());
            if (!equals) {
                return Result.error("无权限修改该考试成绩");
            }

            // 更新成绩
            score.setScore(new java.math.BigDecimal(newScore));
            boolean updated = scoresService.updateById(score);

            if (updated) {
                return Result.success("成绩更新成功");
            } else {
                return Result.error("成绩更新失败");
            }
        } catch (Exception e) {
            return Result.error("成绩更新异常: " + e.getMessage());
        }
    }
}